import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:netflix_social/constants/app_constants.dart';
import 'package:netflix_social/models/video.dart';
import 'package:netflix_social/providers/video_provider.dart';
import 'package:netflix_social/theme/app_theme.dart';
import 'package:video_player/video_player.dart';
import 'package:provider/provider.dart';

class PlayerScreen extends StatefulWidget {
  final String videoId;
  final bool isOffline;

  const PlayerScreen({
    Key? key,
    required this.videoId,
    this.isOffline = false,
  }) : super(key: key);

  @override
  State<PlayerScreen> createState() => _PlayerScreenState();
}

class _PlayerScreenState extends State<PlayerScreen> {
  late VideoPlayerController _controller;
  bool _isControlsVisible = true;
  bool _isPlaying = false;
  bool _isInitialized = false;
  bool _isFullScreen = false;
  Timer? _controlsTimer;
  Duration _currentPosition = Duration.zero;
  Duration _videoDuration = Duration.zero;
  Video? _video;

  @override
  void initState() {
    super.initState();
    _initializePlayer();
    
    // 设置横屏
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);
    
    // 全屏模式
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
  }

  @override
  void dispose() {
    _controller.dispose();
    _controlsTimer?.cancel();
    
    // 恢复竖屏
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    
    // 恢复系统UI
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: SystemUiOverlay.values);
    
    super.dispose();
  }

  Future<void> _initializePlayer() async {
    final videoProvider = Provider.of<VideoProvider>(context, listen: false);
    
    // 获取视频详情
    _video = await videoProvider.getVideoDetails(widget.videoId);
    
    if (_video == null) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('无法加载视频')),
        );
        Navigator.pop(context);
      }
      return;
    }
    
    // 初始化视频控制器
    final videoUrl = widget.isOffline
        ? _video!.offlineUrl ?? _video!.videoUrl
        : _video!.videoUrl;
    
    _controller = VideoPlayerController.network(videoUrl);
    
    try {
      await _controller.initialize();
      _controller.addListener(_videoListener);
      setState(() {
        _isInitialized = true;
        _videoDuration = _controller.value.duration;
      });
      
      // 自动播放
      _playVideo();
      
      // 更新观看历史
      if (!widget.isOffline) {
        videoProvider.addToHistory(widget.videoId);
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('视频播放错误: $e')),
        );
      }
    }
  }

  void _videoListener() {
    if (!mounted) return;
    
    setState(() {
      _currentPosition = _controller.value.position;
      _isPlaying = _controller.value.isPlaying;
      
      // 检查是否播放结束
      if (_controller.value.position >= _controller.value.duration) {
        _isPlaying = false;
        _showControls();
      }
    });
  }

  void _playVideo() {
    _controller.play();
    setState(() {
      _isPlaying = true;
    });
    _startControlsTimer();
  }

  void _pauseVideo() {
    _controller.pause();
    setState(() {
      _isPlaying = false;
    });
    _showControls();
  }

  void _togglePlayPause() {
    if (_isPlaying) {
      _pauseVideo();
    } else {
      _playVideo();
    }
  }

  void _showControls() {
    setState(() {
      _isControlsVisible = true;
    });
    _startControlsTimer();
  }

  void _hideControls() {
    if (_isPlaying) {
      setState(() {
        _isControlsVisible = false;
      });
    }
  }

  void _startControlsTimer() {
    _controlsTimer?.cancel();
    _controlsTimer = Timer(const Duration(seconds: 3), _hideControls);
  }

  void _seekTo(Duration position) {
    _controller.seekTo(position);
    _startControlsTimer();
  }

  void _toggleFullScreen() {
    setState(() {
      _isFullScreen = !_isFullScreen;
    });
    _startControlsTimer();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: _isInitialized
          ? _buildVideoPlayer()
          : const Center(
              child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(AppTheme.netflixRed),
              ),
            ),
    );
  }

  Widget _buildVideoPlayer() {
    return GestureDetector(
      onTap: _showControls,
      child: Stack(
        fit: StackFit.expand,
        children: [
          // 视频播放器
          Center(
            child: AspectRatio(
              aspectRatio: _controller.value.aspectRatio,
              child: VideoPlayer(_controller),
            ),
          ),
          
          // 控制层
          AnimatedOpacity(
            opacity: _isControlsVisible ? 1.0 : 0.0,
            duration: const Duration(milliseconds: 300),
            child: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    Colors.black.withOpacity(0.7),
                    Colors.transparent,
                    Colors.transparent,
                    Colors.black.withOpacity(0.7),
                  ],
                  stops: const [0.0, 0.3, 0.7, 1.0],
                ),
              ),
              child: _isControlsVisible
                  ? Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        // 顶部控制栏
                        _buildTopControls(),
                        
                        // 中央播放/暂停按钮
                        Center(
                          child: IconButton(
                            icon: Icon(
                              _isPlaying ? Icons.pause_circle_filled : Icons.play_circle_filled,
                              size: 70,
                              color: Colors.white,
                            ),
                            onPressed: _togglePlayPause,
                          ),
                        ),
                        
                        // 底部控制栏
                        _buildBottomControls(),
                      ],
                    )
                  : const SizedBox.shrink(),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTopControls() {
    return SafeArea(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            // 返回按钮
            IconButton(
              icon: const Icon(
                Icons.arrow_back,
                color: Colors.white,
              ),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
            
            // 视频标题
            if (_video != null)
              Expanded(
                child: Text(
                  _video!.title,
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                  textAlign: TextAlign.center,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            
            // 设置按钮
            IconButton(
              icon: const Icon(
                Icons.settings,
                color: Colors.white,
              ),
              onPressed: () {
                _showSettingsBottomSheet();
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBottomControls() {
    return SafeArea(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            // 进度条
            Row(
              children: [
                // 当前时间
                Text(
                  _formatDuration(_currentPosition),
                  style: const TextStyle(color: Colors.white),
                ),
                
                // 进度滑块
                Expanded(
                  child: Slider(
                    value: _currentPosition.inMilliseconds.toDouble(),
                    min: 0.0,
                    max: _videoDuration.inMilliseconds.toDouble(),
                    activeColor: AppTheme.netflixRed,
                    inactiveColor: Colors.grey[600],
                    onChanged: (value) {
                      setState(() {
                        _currentPosition = Duration(milliseconds: value.toInt());
                      });
                    },
                    onChangeEnd: (value) {
                      _seekTo(Duration(milliseconds: value.toInt()));
                    },
                  ),
                ),
                
                // 总时长
                Text(
                  _formatDuration(_videoDuration),
                  style: const TextStyle(color: Colors.white),
                ),
              ],
            ),
            
            // 控制按钮行
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                // 快退10秒
                IconButton(
                  icon: const Icon(
                    Icons.replay_10,
                    color: Colors.white,
                    size: 30,
                  ),
                  onPressed: () {
                    final newPosition = _currentPosition - const Duration(seconds: 10);
                    _seekTo(newPosition.isNegative ? Duration.zero : newPosition);
                  },
                ),
                
                // 播放/暂停
                IconButton(
                  icon: Icon(
                    _isPlaying ? Icons.pause : Icons.play_arrow,
                    color: Colors.white,
                    size: 30,
                  ),
                  onPressed: _togglePlayPause,
                ),
                
                // 快进10秒
                IconButton(
                  icon: const Icon(
                    Icons.forward_10,
                    color: Colors.white,
                    size: 30,
                  ),
                  onPressed: () {
                    final newPosition = _currentPosition + const Duration(seconds: 10);
                    _seekTo(newPosition > _videoDuration ? _videoDuration : newPosition);
                  },
                ),
                
                // 全屏
                IconButton(
                  icon: Icon(
                    _isFullScreen ? Icons.fullscreen_exit : Icons.fullscreen,
                    color: Colors.white,
                    size: 30,
                  ),
                  onPressed: _toggleFullScreen,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
    return '${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds';
  }

  void _showSettingsBottomSheet() {
    showModalBottomSheet(
      context: context,
      backgroundColor: AppTheme.cardColor,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(16),
        ),
      ),
      builder: (context) {
        return ListView(
          shrinkWrap: true,
          children: [
            ListTile(
              leading: const Icon(Icons.speed, color: Colors.white),
              title: const Text('播放速度'),
              trailing: DropdownButton<double>(
                value: _controller.value.playbackSpeed,
                dropdownColor: AppTheme.cardColor,
                underline: Container(),
                items: [0.5, 0.75, 1.0, 1.25, 1.5, 2.0].map((speed) {
                  return DropdownMenuItem<double>(
                    value: speed,
                    child: Text(
                      '${speed}x',
                      style: const TextStyle(color: Colors.white),
                    ),
                  );
                }).toList(),
                onChanged: (value) {
                  if (value != null) {
                    _controller.setPlaybackSpeed(value);
                    Navigator.pop(context);
                    _startControlsTimer();
                  }
                },
              ),
            ),
            ListTile(
              leading: const Icon(Icons.subtitles, color: Colors.white),
              title: const Text('字幕'),
              trailing: const Icon(Icons.arrow_forward_ios, color: Colors.grey, size: 16),
              onTap: () {
                // 打开字幕设置
                Navigator.pop(context);
                // 实际项目中，这里可能会显示字幕设置
              },
            ),
            ListTile(
              leading: const Icon(Icons.high_quality, color: Colors.white),
              title: const Text('画质'),
              trailing: const Icon(Icons.arrow_forward_ios, color: Colors.grey, size: 16),
              onTap: () {
                // 打开画质设置
                Navigator.pop(context);
                // 实际项目中，这里可能会显示画质设置
              },
            ),
            ListTile(
              leading: const Icon(Icons.report, color: Colors.white),
              title: const Text('举报问题'),
              onTap: () {
                // 举报问题
                Navigator.pop(context);
                // 实际项目中，这里可能会导航到举报页面
              },
            ),
          ],
        );
      },
    ).then((_) => _startControlsTimer());
  }
}
